package com.tsingteng.cosfun.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Build;
import android.os.Handler;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.TextView;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.tsingteng.cosfun.MainActivity;
import com.tsingteng.cosfun.R;
import com.tsingteng.cosfun.app.AppContext;
import com.tsingteng.cosfun.common.Config;
import com.tsingteng.cosfun.common.Navigate;
import com.tsingteng.cosfun.helper.DialogHelper;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.UUID;


/**
 * 描述: app工具类
 * 创建人: 肖利
 * 时间: 2018/7/30
 * qq: (872179966)
 */

public class AppUtils {


    private static boolean isOutLogon = false;

    public static boolean isHuaZhongHua = false;

    /**
     * 获取对应的版本号
     *
     * @return
     */
    public static int getAppVersion() {
        try {
            PackageInfo info = AppContext.getContext().getPackageManager().getPackageInfo(
                    AppContext.getContext().getPackageName(), 0);
            return info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return 1;
    }


    /**
     * 获取对应的版本名称
     *
     * @return
     */
    public static String getVersionName() {
        PackageManager manager = AppContext.getContext().getPackageManager();
        String name = null;
        try {
            PackageInfo info = manager.getPackageInfo(AppContext.getContext().getPackageName(), 0);
            name = info.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }

        return name;
    }






    /**
     * 设备名称
     *
     * @return
     */
    public static String getAppPhoneName() {
        String phoneName = Build.MODEL;
        return phoneName;
    }


    /**
     * sdk版本
     *
     * @return
     */
    public static String getAppPhoneSDK() {
        String phoneSDK = Build.VERSION.RELEASE;
        return phoneSDK;

    }

    /**
     * 获取手机厂商
     *
     * @return 手机厂商
     */
    public static String getDeviceBrand() {
        return android.os.Build.BRAND;
    }

    /**
     * 获取当前手机系统语言。
     *
     * @return 返回当前系统语言。例如：当前设置的是“中文-中国”，则返回“zh-CN”
     */
    public static String getSystemLanguage() {
        return Locale.getDefault().getLanguage();
    }


    public static void setLoginTag(String type) {
        SPUtils.init().putString(Config.LOGIN_TYPE, type);
    }

    public static String getLoginTag() {
        return SPUtils.init().getString(Config.LOGIN_TYPE);
    }

    public static void setWXLoginOrShareTag(String type) {
        SPUtils.init().putString(Config.WX_TAG, type);
    }

    public static String getWXLoginOrShareTag() {
        return SPUtils.init().getString(Config.WX_TAG);
    }

    /**
     * 标记app是否登录
     *
     * @param isLogin
     */
    public static void setIsLogin(boolean isLogin) {
        SPUtils.init().putBoolean(Config.IS_LOGIN, isLogin);
    }


    public static boolean getIsLogin() {
        return SPUtils.init().getBoolean(Config.IS_LOGIN, false);
    }


    /**
     * 得到屏幕的高和宽
     *
     * @param activity
     * @return
     */
    public static int[] getScreenWidthAndHeight(Activity activity) {
        int[] screen = new int[2];
        WindowManager wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(dm);
        int width = dm.widthPixels;         // 屏幕宽度（像素）
        int height = dm.heightPixels;       // 屏幕高度（像素）
        float density = dm.density;         // 屏幕密度（0.75 / 1.0 / 1.5）
        int screenWidth = (int) (width / density);  // 屏幕宽度(dp)
        int screenHeight = (int) (height / density);// 屏幕高度(dp)
        screen[0] = width;
        screen[1] = height;
        return screen;
    }

    /**
     * 保存摄像头的状态
     *
     * @param status true正 false 反
     */
    public static void setSwitchCameraStatus(boolean status) {
        SPUtils.init().putBoolean("switchCamera", status);
    }

    /**
     * 得到摄像头的状态
     *
     * @return
     */
    public static boolean getSwitchCameraStatus() {
        return SPUtils.init().getBoolean("switchCamera",true);
    }


    /**
     * 得到设备id
     *
     * @return
     */
    public static String getMobileId() {
        String mobileId = SPUtils.init().getString("mobileId");
        if (TextUtils.isEmpty(mobileId)) {
            SPUtils.init().putString("mobileId", String.valueOf(System.currentTimeMillis()) + "android" + UUID.randomUUID().toString());
        }
        return SPUtils.init().getString("mobileId");
    }

    /**
     * 得到gid
     */
    public static void setGid() {
        //为空的话储存里面去
        if (TextUtils.isEmpty(SPUtils.init().getString("gid")))
            SPUtils.init().putString("gid", getIMEI(AppContext.getContext()));
    }

    /**
     * 得到gid
     *
     * @return
     */
    public static String getGid() {
        return SPUtils.init().getString("gid");
    }

    /**
     * 得到通知类型的数量
     *
     * @return
     */
    public static boolean getMessageNumber() {
        int fansCount = AppUtils.getMessageNumber("FANS");
        int pointCount = AppUtils.getMessageNumber("POINT");
        int commentCount = AppUtils.getMessageNumber("REVIEW");
        int greatCount = AppUtils.getMessageNumber("FAVOR");
        return (fansCount+ pointCount+commentCount+ greatCount)==0?false:true;
    }

    /**
     * 得到通知类型的数量
     *
     * @param type
     * @return
     */
    public static int getMessageNumber(String type) {
        return SPUtils.init().getInt(type);
    }

    /**
     * 设置通知类型的数量
     *
     * @param type
     */
    public static void setMessageNumber(String type, int value) {
        if (value == 0) {
            SPUtils.init().putInt(type, 0);
        } else {
            SPUtils.init().putInt(type, getMessageNumber(type) + value);
        }

    }


    /**
     * 根据城市ID获取城市名称
     *
     * @param cityId 城市ID
     * @return 城市名称
     */

    public static String getCityName(Context context, String cityId) {
        String json = jsonFormAssets(context, "city.json");
        JSONArray array = JSON.parseArray(json);
        for (int i = 0; i < array.size(); i++) {
            JSONObject object = array.getJSONObject(i);
            JSONArray cities = JSON.parseArray(object.getString("cities"));
            for (int j = 0; j < cities.size(); j++) {
                JSONObject obj = cities.getJSONObject(j);
                if (obj.getString("areaId").equals(cityId)) {
                    return obj.getString("areaName");
                }
            }
        }
        return "北京市";
    }


    /**
     * 读取本地 assets 内的文件
     *
     * @param context  上下文
     * @param fileName 文件名
     * @return String字符串
     */
    public static String jsonFormAssets(Context context, String fileName) {
        StringBuilder sb = new StringBuilder();
        AssetManager am = context.getAssets();
        BufferedReader br = null;
        try {
            br = new BufferedReader(new InputStreamReader(
                    am.open(fileName)));
            String next = "";
            while (null != (next = br.readLine())) {
                sb.append(next);
            }
        } catch (IOException e) {
            LogUtils.e("Exception", e.getMessage());
            sb.delete(0, sb.length());
        } finally {
            try {
                if (br != null) br.close();
            } catch (IOException e) {
                LogUtils.e("Exception", e.getMessage());
            }
        }
        return sb.toString().trim();
    }


    public static String getIMEI(Context context) {

        String SerialNumber = android.os.Build.SERIAL;
        return SerialNumber;
    }

    /**
     * 存放系统通知时间
     *
     * @param creatTime
     */
    public static void setNotificationTime(long creatTime) {
        SPUtils.init().putLong("NotificationTime", creatTime);
    }

    /**
     * 获取系统通知时间
     */
    public static long getNotificationTime() {
        return SPUtils.init().getLong("NotificationTime", System.currentTimeMillis());
    }

    /**
     * 存放官方通知时间
     *
     * @param creatTime
     */
    public static void setOfficialTime(long creatTime) {
        SPUtils.init().putLong("OfficialTime", creatTime);
    }

    /**
     * 获取官方通知时间
     */
    public static long getOfficialTime() {
        return SPUtils.init().getLong("OfficialTime", System.currentTimeMillis());
    }


    /**
     * 保存 美颜等级
     *
     * @param level
     */
    public static void setBeautyParameterLevel(int level) {
        SPUtils.init().putInt("meihua", level);
    }

    /**
     * 得到美颜等级
     */
    public static int getBeautyParameterLevel() {
        return SPUtils.init().getInt("meihua", -1);
    }

    /**
     * 保存 滤镜等级
     *
     * @param level
     */
    public static void setBeautyFilterLevel(int level) {
        SPUtils.init().putInt("filter", level);
    }

    /**
     * 滤镜等级
     */
    public static int getBeautyFilterLevel() {
        return SPUtils.init().getInt("filter", -1);
    }

    /**
     * 设置自定义等级
     *
     * @param arrayList
     */
    public static void setSelfBeautyLevel(ArrayList<Float> arrayList) {
        SPUtils.init().putData("selfBeauty", arrayList);
    }

    /**
     * 得到自定义等等级
     */
    public static ArrayList<Float> getSelfBeautyLevel() {
        return SPUtils.init().getDataList("selfBeauty");
    }

    /**
     * 设置自定义等级的点击事件
     */
    public static void setSelfBeautyLevelClick(int positiom) {
        SPUtils.init().putInt("SelfBeautyLevelClick", positiom);
    }

    /**
     * 得到自定义等等级的点击事件
     */
    public static int getSelfBeautyLevelClick() {
        return SPUtils.init().getInt("SelfBeautyLevelClick", -1);
    }

    /**
     * 获取app当前的渠道号或application中指定的meta-data
     *
     * @return 如果没有获取成功(没有对应值，或者异常)，则返回值为空
     */
    public static Integer getAppMetaData(Context context, String key) {
        if (context == null || TextUtils.isEmpty(key)) {
            return 0;
        }
        int channelNumber = 0;
        try {
            PackageManager packageManager = context.getPackageManager();
            if (packageManager != null) {
                ApplicationInfo applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
                if (applicationInfo != null) {
                    if (applicationInfo.metaData != null) {
                        String channelName = applicationInfo.metaData.getString(key);
                        switch (channelName) {
                            case "OFFICIAL_ASSISTANT":
                                channelNumber = 0;
                                break;
                            case "DEV_360":
                                channelNumber = 2;
                                break;
                            case "WANDOUJIA":
                                channelNumber = 3;
                                break;
                            case "ANZHI":
                                channelNumber = 4;
                                break;
                            case "APP_BAIDU":
                                channelNumber = 5;
                                break;
                            case "XIAOMI":
                                channelNumber = 6;
                                break;
                            case "FLYME":
                                channelNumber = 7;
                                break;
                            case "MUMAYI":
                                channelNumber = 8;
                                break;
                            case "OPEN_QQ":
                                channelNumber = 9;
                                break;
                            case "APPCHINA":
                                channelNumber = 10;
                                break;
                            case "APPS_UC":
                                channelNumber = 11;
                                break;
                            case "LENOVO":
                                channelNumber = 12;
                                break;
                            case "OPPOMOBILE":
                                channelNumber = 13;
                                break;
                            case "SOGOU":
                                channelNumber = 14;
                                break;
                            case "YUNOS":
                                channelNumber = 15;
                                break;
                            case "HUAWEI":
                                channelNumber = 1;
                                break;
                            case "APPSTORE":
                                channelNumber = 18;
                                break;
                            case "VIVO":
                                channelNumber = 17;
                                break;
                            case "GUANGFANG_1":
                                channelNumber = 901;
                                break;
                            case "GUANGFANG_2":
                                channelNumber = 902;
                                break;
                            case "GUANGFANG_3":
                                channelNumber = 903;
                                break;
                            case "GUANGFANG_4":
                                channelNumber = 904;
                                break;
                            case "GUANGFANG_5":
                                channelNumber = 905;
                                break;
                            default:
                                channelNumber = 19;
                                break;


                        }
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }


        return Integer.valueOf(channelNumber);
    }

    /**
     * 弹窗提示(显示时间1500ms)
     * @param text
     */
    public static void  showHintDialogToast(Context context,String text) {
        DialogHelper.showHintToast(context,text);
    }


    /**
     * 是否要进入登录页面(默认进入,只有首页不进入)
     * @return
     */
    public static boolean isToLogonActivity() {
        return SPUtils.init().getBoolean("isToLogonActivity",true);
    }


    /**
     * 设置是否进入登录页面
     * @param isToLogonActivity
     */
    public static void setToLogonActivity(boolean isToLogonActivity) {
        SPUtils.init().putBoolean("isToLogonActivity",isToLogonActivity);
    }

    /**
     * 存放聊天时间
     */
    public static void setChatTime() {
        SPUtils.init().putLong("chatTime",System.currentTimeMillis());
    }

    /**
     * 得到聊天时间
     * @return
     */
    public static long getChatTime() {
        return SPUtils.init().getLong("chatTime",0);
    }



    /**
     * 存放上次新增关注的数量
     */
    public static void setFollowCount(int followCount) {
        SPUtils.init().putInt("FollowCount",followCount);
    }

    /**
     * 得到
     * @return上次新增关注的数量
     */
    public static int getFollowCount() {
        return SPUtils.init().getInt("FollowCount",0);
    }

    /**
     * 存放上次新增关注的shijian
     */
    public static void setFollowTime(long followTime) {
        SPUtils.init().putLong("FollowTime",followTime);
    }

    /**
     * 得到
     * @return上次新增关注的shijian
     */
    public static long getFollowTime() {
        return SPUtils.init().getLong("FollowTime",-1);
    }


    /**
     * 是否有异常
     * @return
     */
    public static String isHaveException() {
        return SPUtils.init().getString("HaveException");
    }


    /**
     * 设置异常
     * @param isException
     */
    public static void setHaveException(String isException) {
         SPUtils.init().putString("HaveException",isException);
    }


    /**
     * s是否显示网络弹窗（）
     * @param isShowNetDialog
     */
    public static void setIsShowNetDialog(boolean isShowNetDialog) {
        SPUtils.init().putBoolean("isShowNetDialog",isShowNetDialog);
    }
    public static boolean isShowNetDialog() {
        return SPUtils.init().getBoolean("isShowNetDialog",true);
    }
}
